﻿using Api1.Model;
using Api1.Service;
using Api1.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Api1
{
    /// <summary>
    /// 闸机通用接口
    /// </summary>
    public class ApiServiceImpl
    {
        /// <summary>
        /// 进场刷卡
        /// </summary>
        /// <param name="card_no"></param>
        /// <param name="brakemachine_no"></param>
        /// <returns></returns>
        public static Dictionary<string, object> inSwipeCard(string card_no, string brakemachine_no,String cabinet_no="")
        {
            //获取原卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);
            Dictionary<String, Object> face_code = null;//人脸模板
            if (interfaces == null)
            {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("100000"));
                return getResult(false, GetError("100000"), false);
            }
            ////是否验证进场和出场
            //int InOrOutVarify = BehaviorLogService.GetInstance().IsInOrOutVarify(card_no, brakemachine_no);
            //if (InOrOutVarify == -1)
            //{//没有出场
            //    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100003"), brakemachine_no);
            //    return getResult(false, GetError("100003"), false);
            //}else if (InOrOutVarify == -2)
            //    {//没有进场
            //        BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100004"), brakemachine_no);
            //        return getResult(false, GetError("100004"), false);
            //    }
            if (interfaces.Owner_Type == 1)
            {//会员卡
                if (interfaces.Membership_Type == 1 || interfaces.Membership_Type == 3)
                {// 次卡 或者储值卡
                        //是否在免扣时间范围内
                        Boolean is_in_free_time = InterfaceService.GetInstance().Is_In_Free_Time(interfaces.Card_No);
                        if (is_in_free_time)
                        {//在免扣时间范围内 直接通行
                            BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                            return getResult(true, "", true);
                        }
                }
                else if (interfaces.Membership_Type == 2)
                {//年月卡
                    if (interfaces.In_Varifycation == 0)
                    {//无需验证的情况---放行
                       // BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                       // return getResult(true, "", true);
                    }   
                }
                else
                {
                    ///安科系统中其他卡种
                    return getResult(false, GetError("100012"), false);
                }
                /////////////////////////////闸机验证（指纹或人脸或其他）////////
                if (interfaces.In_Varifycation == 1 && interfaces.In_Varifycation_Type == 1)
                {//需要验证，且是指纹验证
                    if (String.IsNullOrWhiteSpace(interfaces.FingerPrint) || interfaces.FingerPrint.Length < 500)
                    {//指纹模板错误
                       // BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100016"), brakemachine_no);
                        //return getResult(false, GetError("100016"), false);
                    }
                }
                else if (interfaces.In_Varifycation == 1 && interfaces.In_Varifycation_Type == 2)
                {//需要验证，且是人脸验证            
                    face_code = InterfaceService.GetInstance().GetFaceCode(interfaces.Card_No);
                    if (face_code == null)
                    {//人脸模板错误
                       // BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100017"), brakemachine_no);
                       // return getResult(false, GetError("100017"), false);
                    }
                }
                else if (interfaces.In_Varifycation == 1 && interfaces.In_Varifycation_Type == 3)
                {//需要验证，且是前台验证
                    Int32 varify_record_id = InterfaceService.GetInstance().GetVarifyRecord(interfaces.Card_No);
                    if (varify_record_id < 1)
                    {//前台没有验证通过
                        BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100015"), brakemachine_no);
                        return getResult(false, GetError("100015"), false);
                    }
                }
                ////////////////////////////////卡在我们系统处于正常情况则调用第三方系统接口///////////////////////////////////////

                Dictionary<String, object> anke_result = OcmApiService.GetInstance().CheckIn(interfaces.Contract_Id, interfaces.Member_Id,card_no);
                if (Convert.ToBoolean(anke_result["Flag"]))
                {//安科系统验证通过
                    if (interfaces.In_Varifycation_Type == 1)
                    {//指纹
                     //新增一个刷卡记录
                        BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                        return getResult(true, interfaces.FingerPrint, false, "1");
                    }
                    else if (interfaces.In_Varifycation_Type == 2)
                    {//人脸
                        BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                        return getResult(true, face_code["face1"].ToString() + "," + face_code["face2"].ToString() + "," + face_code["face3"].ToString(), false, "2");
                    }
                    else if (interfaces.In_Varifycation_Type == 3)
                    {//前台                       
                        InterfaceService.GetInstance().UpdateVarifyRecord(interfaces.Card_No);
                    }
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                    return getResult(true, "", true);
                }
                else
                {
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, anke_result["Msg"].ToString(), brakemachine_no);
                    return getResult(false, anke_result["Msg"].ToString(), false);
                }

            }
            else if (interfaces.Owner_Type == 2)
                {//员工卡
                 //入场日志
                    if (interfaces.In_Varifycation_Type == 1)
                    {//指纹
                        if (String.IsNullOrWhiteSpace(interfaces.FingerPrint)||interfaces.FingerPrint.Length<500){
                            BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100016"), brakemachine_no);
                            return getResult(false, GetError("100016"), false);
                        }
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                    return getResult(true, interfaces.FingerPrint, false, "1");
                    }
                    else if (interfaces.In_Varifycation_Type == 2)
                    {//人脸
                        face_code = InterfaceService.GetInstance().GetFaceCode(interfaces.Card_No);
                        if (face_code == null)
                        {//人脸模板错误
                            BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100017"), brakemachine_no);
                            return getResult(false, GetError("100017"), false);
                        }
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                    return getResult(true, face_code["face1"].ToString() + "," + face_code["face2"].ToString() + "," + face_code["face3"].ToString(), false, "2");
                    }                   
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                    return getResult(true, "", true);
                }
            else if (interfaces.Owner_Type == 3)
                {// 临时卡
                 //是否在免扣时间范围内
                    Boolean is_in_free_time = InterfaceService.GetInstance().Is_In_Free_Time(interfaces.Card_No);
                    if (is_in_free_time)
                    {//在免扣时间范围类 直接通行
                        BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no);
                        return getResult(true, "", true);
                    }
                    //卡余次是否够用
                    if (interfaces.Surplus_Num < 1)
                    {
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces,2,GetError("100019"),brakemachine_no);
                        return getResult(false, GetError("100019"), false);
                    }
                    //卡次数减一
                    InterfaceService.GetInstance().SetDes(interfaces);
                    //入场日志
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 1, "", brakemachine_no,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    return getResult(true, "", true);
                }
            else
                {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("000000"));
                return getResult(false, GetError("100012"), false);
                }             
        }
        /// <summary>
        /// 出场刷卡
        /// </summary>
        /// <param name="card_no">卡号</param>
        /// <param name="brakemachine_no">闸机编号</param>
        /// <param name="cabinet_no">柜子号</param>
        /// <param name="current_cabinet_no">当前使用柜子号</param>
        /// <returns></returns>
        public static Dictionary<string, object> outSwipeCard(string card_no, string brakemachine_no,String cabinet_no="",int has_store=0) {
            //获取原卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);            
            if (interfaces == null)
            {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("100000"));
                return getResult(false, GetError("100000"), false);
            }
            //新增柜子使用记录
            CabinetService.GetInstance().AddCabinet(interfaces, cabinet_no);
            int temp_open=BehaviorLogService.GetTempOut();
            if (temp_open == 0) {// 不开启临时出场
                if (has_store != 0) {//存了东西
                    BehaviorLogService.GetInstance().AddOutBrackmachineBehavior(card_no, brakemachine_no,"1");
                    return getResult(false, GetError("100021"), false);
                }
            }
            //是否验证进场和出场
            int InOrOutVarify = BehaviorLogService.GetInstance().IsInOrOutVarify(card_no, brakemachine_no,interfaces.Owner_Type);
            if (InOrOutVarify == -1)
            {//没有出场
                BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100003"), brakemachine_no);
                return getResult(false, GetError("100003"), false);
            }
            else if (InOrOutVarify == -2)
            {//没有进场
                BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100004"), brakemachine_no);
                return getResult(false, GetError("100004"), false);
            }
            OcmApiService.GetInstance().CheckOut(card_no);
            BehaviorLogService.GetInstance().AddOutBrackmachineBehavior(card_no,brakemachine_no);
            return getResult(true, "",true);
        }
        /// <summary>
        /// 生物识别验证回调用
        /// </summary>
        /// <param name="card_no"></param>
        /// <param name="flag"></param>
        /// <param name="brakemachine_no"></param>
        public static void swipeFingerPrintResult(string card_no, bool flag, string brakemachine_no) {
            //获取原卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            Interfaces interfaces=  InterfaceService.GetInstance().FindByCardno(card_no);

            if (interfaces != null)
            {
                if (flag)
                {
                    BehaviorLogService.GetInstance().AddVarifyBehavior(interfaces, 1, "", brakemachine_no);
                }
                else
                {
                    if (interfaces.In_Varifycation_Type == 1)
                    {/// 指纹
                        BehaviorLogService.GetInstance().AddVarifyBehavior(interfaces, 2, GetError("100006"), brakemachine_no);
                    }
                    else if (interfaces.In_Varifycation_Type == 2)
                    { ///人脸
                        BehaviorLogService.GetInstance().AddVarifyBehavior(interfaces, 2, GetError("100018"), brakemachine_no);
                    }
                }

            }
            else {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("100000"));
            }
        }

        /// <summary>
        ///  获取验证特征码
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> getCharacteristic(String card_no,String brakemachine_no,String cabinet_no) { 
            //获取原卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);
           
            if (interfaces == null)
            {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("100000"));
                return getResult(false, GetError("100000"), false);
            }
           
            //新增柜子使用记录
            CabinetService.GetInstance().AddCabinet(interfaces, cabinet_no);

            if (interfaces.Owner_Type == 1) {
                String api_type=OperateIniFile.ReadIniData("APITYPE", "Type", "1");
                if (!api_type.Equals("5")) {
                    //获取合同号
                    Dictionary<String, Object> obj = OcmApiService.GetInstance().GetContractInfo(card_no);
                    if (!Convert.ToBoolean(obj["Flag"]))
                    {
                        BehaviorLogService.GetInstance().AddVarifyBehavior(interfaces, 2, "无效的卡(ak)", brakemachine_no);
                        return getResult(false, "无效的卡(ak)", false);

                    }
                }
            }

            //是否验证进场和出场
            int InOrOutVarify = BehaviorLogService.GetInstance().IsInOrOutVarify(card_no, brakemachine_no,interfaces.Owner_Type);
            if (InOrOutVarify == -1)
            {//没有出场
                BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100003"), brakemachine_no);
                return getResult(false, GetError("100003"), false);
            }
            else if (InOrOutVarify == -2)
            {//没有进场
                BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100004"), brakemachine_no);
                return getResult(false, GetError("100004"), false);
            }

            Dictionary<String, Object> face_code = null;//人脸模板
            if (interfaces.In_Varifycation == 1 && interfaces.In_Varifycation_Type == 1)
            {//需要验证，且是指纹验证
                if (String.IsNullOrWhiteSpace(interfaces.FingerPrint) || interfaces.FingerPrint.Length < 500)
                {//指纹模板错误
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100016"), brakemachine_no);
                    return getResult(false, GetError("100016"), false);
                }
                return getResult(true, interfaces.FingerPrint, false, "1");
            }
            else if (interfaces.In_Varifycation == 1 && interfaces.In_Varifycation_Type == 2)
            {//需要验证，且是人脸验证            
                face_code = InterfaceService.GetInstance().GetFaceCode(interfaces.Card_No);
                if (face_code == null)
                {//人脸模板错误
                    BehaviorLogService.GetInstance().AddInBrackmachineBehavior(interfaces, 2, GetError("100017"), brakemachine_no);
                    return getResult(false, GetError("100017"), false);
                }
                return getResult(true, combin_face_code(card_no, interfaces.In_Varifycation_Type.ToString(), face_code), false, "2");
            }

            Dictionary<String, Object> result = inSwipeCard(card_no, brakemachine_no,cabinet_no);
            if (Convert.ToBoolean(result["flag"])&&interfaces.Owner_Type==1)
            {
                result["member"] = ApiServiceImpl.GetContractInfo(card_no);
            }
            return result;
            //return getResult(true, "", false, "0");
        }
        /// <summary>
        /// 返回给闸机的结果集合
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="data"></param>
        /// <param name="is_open"></param>
        /// <param name="type">1指纹 2人脸 </param>
        /// <returns></returns>
        public static Dictionary<string, object> getResult(bool flag, string data, bool is_open,String varify_type = "0")
        {
            //用户返回结果集
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("flag", flag);
            result.Add("data", data);
            result.Add("is_open", is_open);
            result.Add("varify_type", varify_type);
            result.Add("member", null);
            return result;
        }

        public static Dictionary<String, String> GetContractInfo(String card_no) {
           Dictionary<String, Object>  obj= OcmApiService.GetInstance().GetContractInfo(card_no);
           int []obj1 = BehaviorLogService.GetInstance().GetStatistic(card_no);
            if (Convert.ToBoolean(obj["Flag"])) {
                Dictionary<String, String> data= (Dictionary<String, String>)(obj["Data"]);
                Dictionary<String,String>  dictionary= new Dictionary<String, String>();
                dictionary.Add("name", data["MemberName"].ToString());
                dictionary.Add("end_date", data["EndDate"].ToString());
                dictionary.Add("surplus_num", data["SurplusNum"].ToString());
                dictionary.Add("cur_month_times", obj1[0]+"");
                dictionary.Add("cur_month_count", obj1[1] + "");
                return dictionary;
            }
            return null;
        }

        /// <summary>
        /// 获取安科错误代码
        /// </summary>
        public static String GetError(String code)
        {
            if (String.IsNullOrWhiteSpace(code))
            {
                return "无效的错误code代码";
            }
            var errorstr = Error[code];
            if (String.IsNullOrWhiteSpace(errorstr))
            {
                return "无效的错误code代码";
            }
            else
            {
                return errorstr;
            }
        }
        public static Dictionary<String, String> Error = new Dictionary<String, String>{
            { "000000","数据库数据错误"},
            { "100000","卡号不存在"},
            { "100003" ,"未按正常程序出闸机"},
            { "100004" ,"未按正常程序进入闸机"},
            { "100006","指纹验证失败"},
            { "100012","卡类型错误"},
            { "100015","没有进行前台验证"},
            { "100016","指纹数据无效"},
            { "100017","人脸模板数据无效"},
            { "100018","人脸验证失败"},
            { "100019","临时卡无效"},
            { "100020","没有内门禁权限"},
            { "100021","物品未取走，请先取走"},

        };

        public static void WriteLog(Type t, Exception ex)
        {
            LogHelper.WriteLog(t, ex);
        }
        /// <summary>
        /// 上传模型数据
        /// </summary>
        /// <param name="card_no"></param>
        /// <param name="Data"></param>
        /// <param name="varify_type"></param>
        public static void UploadModelData(String card_no, String datas,String score, String varify_type)
        {
            InterfaceService.GetInstance().UploadModelData(card_no, datas, score, varify_type);
        }
        public static void WriteLog(Type t, string msg)
        {
            LogHelper.WriteLog(t, msg);
        }
        /// <summary>
        /// 组合指纹数
        /// 
        /// </summary>
        /// <returns></returns>
        protected static String combin_face_code(String card_no, String varify_type, Dictionary<String,Object> face_template) {
            String face_code= face_template["face1"].ToString() + "," + face_template["face2"].ToString() + "," + face_template["face3"].ToString();
            String face_temp = InterfaceService.GetInstance().GetModelData(card_no, varify_type);
            return face_temp+face_code;
        }
        /// <summary>
        /// 刷类门禁
        /// </summary>
        public static Dictionary<string, object> innerDoorSwipe(String card_no,String brakemachine_no) {
            //获取原卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);
            if (interfaces == null)
            {
                LogHelper.WriteLog(typeof(ApiServiceImpl), GetError("100000"));
                return getResult(false, GetError("100000"), false);
            }
            String doors_auth = interfaces.Doors_Auth;
            if (String.IsNullOrWhiteSpace(doors_auth)) {
                SlidingDoorLogService.GetInstance().AddSlidingDoor(interfaces, 2, GetError("100020"), brakemachine_no, SlidingDoorLogService.GetInstance().GetDoorName(brakemachine_no));
                return getResult(false, GetError("100020"), false);
            }
            //判读是否有权限
            if (InterfaceService.GetInstance().HasAuthCode(doors_auth, brakemachine_no))
            {
                SlidingDoorLogService.GetInstance().AddSlidingDoor(interfaces, 1,"",brakemachine_no,SlidingDoorLogService.GetInstance().GetDoorName(brakemachine_no));
                return getResult(true, "", true);
            }
            else {
                SlidingDoorLogService.GetInstance().AddSlidingDoor(interfaces, 2, GetError("100020"), brakemachine_no, SlidingDoorLogService.GetInstance().GetDoorName(brakemachine_no));
                return getResult(false, GetError("100020"), false);
            }
        }
        /// <summary>
        /// v1升级到v2 更新会员信息
        /// </summary>
        /// <returns></returns>
        public static string UpdateMember() {

            List<TestMember> list=  InterfaceService.GetTestMember();
            if (list == null) {
                return "";
            }

            foreach (var item in list)
            {
                //会员
                if (item.Owner_Type == 1) {
                     Dictionary<String,Object> result = OcmApiService.GetInstance().GetContractInfo(item.Card_No);
                    if (Convert.ToBoolean(result["Flag"])) {
                        String str= JsonConvert.SerializeObject(result["Data"]);
                        Dictionary<String, String> obj= JsonConvert.DeserializeObject<Dictionary<String,String>>(str);
                        Console.WriteLine(obj["Mobile"]);
                        Console.WriteLine(obj["MemberName"]);
                        Console.WriteLine(obj["ContractID"]);
                        Console.WriteLine(obj["MemberID"]);
                        Console.WriteLine(obj["Mobile"]);
                        Console.WriteLine(obj["StartDate"]);
                        Console.WriteLine(obj["EndDate"]);
                        String sql = String.Format("insert into m_interface (card_no,in_varifycation,in_varifycation_type,create_time,mobile,name,owner_type,fingerprint,contract_id,member_id,start_date,end_date,membership_type,contract_status) values ('{0}',1,1,'{1}','{2}','{3}',1,'{4}','{5}','{6}','{7}','{8}','{9}','{10}')", item.Card_No
                        ,item.Create_Time, obj["Mobile"], obj["MemberName"], item.Fingerprint, obj["ContractID"], obj["MemberID"], obj["StartDate"], obj["EndDate"],obj["MembershipType"],obj["ContractStatus"]);
                        InterfaceService.ExcuteSql(sql);
                       
                    }
                }
                //员工
                if (item.Owner_Type == 2)
                {
                    InterfaceService.ExcuteSql(String.Format("insert into m_interface (card_no,in_varifycation,in_varifycation_type,create_time,mobile,name,owner_type) values ('{0}',0,0,'{1}','{2}','{3}',2)",item.Card_No
                        ,item.Create_Time,item.Mobile,item.Name));
                }
            }
            MessageBox.Show("成功");
            return "";
        }
        public static void test() {
            List<Dictionary<String,Object>> list=  InterfaceService.SelectDictionaryList("select id,create_time from m_ad");
            foreach (var item in list)
            {
                var t = item["create_time"];
                if (!(t == null))
                {
                    Console.WriteLine(t.ToString());
                }
                else
                {
                    Console.WriteLine("item 为空");
                }
            }
        }
    }
}
